package cn.tongji.edu.tjmobile;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class LoginFormActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_form);

        LinearLayout loginLayout = (LinearLayout) findViewById(R.id.login_form_layout);
        loginLayout.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);

        TextView confirmTextView = (TextView) findViewById(R.id.confirm_button);
        confirmTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText studentIdEditText = (EditText) findViewById(R.id.student_id_edittext);
                EditText passcodeEditText = (EditText) findViewById(R.id.passcode_edittext);

                String studentId = studentIdEditText.getText().toString();
                String passcode = passcodeEditText.getText().toString();

                LoginTask task = new LoginTask();
                task.execute(new String[]{studentId, passcode});

            }
        });

        TextView cancelTextView = (TextView) findViewById(R.id.cancel_button);
        cancelTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread () {
                    public void run () {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
    }

    class LoginTask extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {
            HttpClient client = new DefaultHttpClient();
            {
                String url = "http://tjis2.tongji.edu.cn:58080/amserver/UI/Login?Login.Token1=" + params[0] + "&Login.Token2=" + params[1] + "&gx_charset=UTF-8";
                HttpPost request = new HttpPost(url);
                try {
                    HttpResponse response = client.execute(request);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuffer buffer = new StringBuffer("");
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line + "\n");
                    }
                    reader.close();
                    String result = buffer.toString();
                    System.out.println(result);
                    if(result.contains("Authentication failed.")){
                        return null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            {
                String url = "http://tjis2.tongji.edu.cn:58080/amconsole/base/AMAdminFrame";
                HttpGet request = new HttpGet(url);
                try {
                    HttpResponse response = client.execute(request);
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                    StringBuffer buffer = new StringBuffer("");
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line + "\n");
                    }
                    reader.close();
                    String result = buffer.toString();

                    Document resultDocument = Jsoup.parse(result);
                    Elements frameElements = resultDocument.select("frame");
                    String srcHeader = frameElements.get(0).attr("src");
                    String srcUserPage = frameElements.get(1).attr("src");

                    String baseUrl = "http://tjis2.tongji.edu.cn:58080";

                    HttpGet headerRequest = new HttpGet(baseUrl + srcHeader);
                    HttpResponse headerResponse = client.execute(headerRequest);

                    BufferedReader headerReader = new BufferedReader(new InputStreamReader(headerResponse.getEntity().getContent()));
                    StringBuffer headerBuffer = new StringBuffer("");
                    String headerLine = "";
                    while ((headerLine = headerReader.readLine()) != null) {
                        headerBuffer.append(headerLine + "\n");
                    }
                    headerReader.close();
                    String headerResult = headerBuffer.toString();

                    HttpGet userPageRequest = new HttpGet(baseUrl + srcUserPage);
                    HttpResponse userPageResponse = client.execute(userPageRequest);

                    BufferedReader userPageReader = new BufferedReader(new InputStreamReader(userPageResponse.getEntity().getContent()));
                    StringBuffer userPageBuffer = new StringBuffer("");
                    String userPageLine = "";
                    while ((userPageLine = userPageReader.readLine()) != null) {
                        userPageBuffer.append(userPageLine + "\n");
                    }
                    userPageReader.close();
                    String userPageResult = userPageBuffer.toString();

                    Document userPageResultDocument = Jsoup.parse(userPageResult);
                    Elements nameInput = userPageResultDocument.select("input");
                    String name = nameInput.get(132).attr("value");

                    response.getEntity().consumeContent();

                    MainActivity.userName = name;
                    MainActivity.userId = params[0];
                    Intent intent = new Intent();
                    intent.putExtra("isLogin", true);
                    intent.setClass(LoginFormActivity.this, MainActivity.class);
                    startActivity(intent);

                    return name;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }
}
